package com.fly.shiroauth.config;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /*
        1. 创建 SimpleAccountRealm 对象
        2. 添加两个用户。参数分别是 username、password、roles
     */
    @Bean
    public Realm realm() {
        SimpleAccountRealm realm = new SimpleAccountRealm();
        realm.addAccount("admin", "123456", "admin");
        realm.addAccount("fly", "123456", "user");
        return realm;
    }

    /*
        1. 创建 DefaultWebSecurityManager 对象
        2. 设置其使用的 Realm
     */
    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm());
        return securityManager;
    }

    /*
        1. 创建 ShiroFilterFactoryBean 对象，用于创建 ShiroFilter 过滤器
        2. 设置 SecurityManager
        3. 设置 URL
        4. 设置 URL 的权限配置
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(this.securityManager());

        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/login_success");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(this.filterChainDefinitionMap());
        return shiroFilterFactoryBean;
    }

    /*
        1. 意要使用有序的 LinkedHashMap ，顺序匹配
     */
    private Map<String, String> filterChainDefinitionMap() {
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/test/echo", "anon"); // 允许匿名访问
        filterMap.put("/test/admin", "roles[admin]"); // 需要 admin 角色
        filterMap.put("/test/normal", "roles[user]"); // 需要 user 角色
        filterMap.put("/logout", "logout"); // 退出
        filterMap.put("/**", "authc"); // 默认剩余的 URL ，需要经过认证
        return filterMap;
    }
}
